<template>
	<section>
		<!--高级查询-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="advancedQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="id" label="ID" width="100" sortable>
			</el-table-column>
			<el-table-column prop="headImage" label="头像" width="150" sortable>
			</el-table-column>
			<el-table-column prop="username" label="姓名" width="100" sortable>
			</el-table-column>
      <el-table-column prop="age" label="年龄" width="100" sortable>
      </el-table-column>
			<el-table-column prop="department.name" label="所属部门" width="100" sortable>
			</el-table-column>
      <el-table-column prop="email" label="邮箱" sortable>
      </el-table-column>

			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<el-button type="danger" size="small" @click="handleSetRole(scope.$index, scope.row)">设置角色</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--批量删除-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger"
                 @click="batchDelete"
                 :disabled="this.sels.length===0"
                 style="float: left;margin: 20px">
        批量删除</el-button>
      <!--分页条-->
      <el-pagination
          style="float: right;margin: 20px"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="pageSizes"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
		</el-col>
		<!--保存界面-->
    <!--
       pros 绑定校验规则名称
       :visible.sync  控制dialog是否显示
       :rules  绑定表单校验规则
       ref="saveForm"  给当前表单取一个别名
    -->
		<el-dialog title="保存"
               :visible.sync="saveFormVisible"
               :close-on-click-modal="false">
			<el-form
          :model="saveForm"
          label-width="80px"
          :rules="saveFormRules"
          ref="saveForm">
        <el-form-item label="头像">
          <el-input v-model="saveForm.headImage" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="姓名">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="saveForm.age" auto-complete="off"></el-input>
				</el-form-item>

        <el-form-item label="所属部门">
          <el-cascader v-model="saveForm.department"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"clearable></el-cascader>
        </el-form-item>

				<el-form-item label="邮箱">
					<el-input type="textarea" v-model="saveForm.email"></el-input>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
        <!--@click.native vue在自定义组件中使用原生事件要加上native-->
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">确认</el-button>
			</div>
		</el-dialog>
    <!--角色界面-->
    <el-dialog title="保存"
               :visible.sync="roleFormVisible"
               :close-on-click-modal="false">
      <el-form
          :model="saveRoleForm"
          label-width="80px"
          :rules="roleFormRules"
          ref="saveRoleForm">
        <el-form-item label="ID">
          {{saveRoleForm.eForm.id}}
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <div class="checkbox-table" v-for="(r,indexkey) in roles" :key="r.id">
            <template>
              <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                           v-model='roleEmp.roleIds' :label="r.id"
                           @change='handleCheck(1,indexkey)'>
                {{r.name}}
              </el-checkbox>
            </template>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--@click.native vue在自定义组件中使用原生事件要加上native-->
        <el-button @click.native="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="roleSubmit" :loading="roleLoading">确认</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>


	export default {
		data() {
			return {
        pageInfo:{
          rows: [],
          total: 0,
        },
        pageSizes:[5, 10, 20, 50],
        //查询对象
        query:{
				  //当前页,默认第一页
          currentPage:1,
          //页面显示数据大小,默认显示5条
          pageSize:5,
          //高级查询关键字
          keyword:""
        },
				listLoading: false,
				sels: [],//列表选中列

        saveFormVisible: false,//新增界面是否显示
        saveLoading: false,
        //校验规则
        saveFormRules: {
					name: [
						{ required: true, message: '请输入名称', trigger: 'blur' }
					]
				},
				//新增界面数据
        saveForm:{
          id:null,
          username: '',
          email:"",
          password:"",
          age:0,
          department:{
            id:null,
            name:""
          },
          headImage:"",
          role :{  //角色表单数据
            id:null,
            name:"",
            sn:"",

          },
        },
        deptTree:[],

        //角色界面数据
        roleFormVisible:false, //控制角色界面显示

        roleFormRules :{  //校验规则

        },
        roleLoading : false, //加载控制

        roles :[],
        saveRoleForm:{
          eForm :{
            id : null
          },
          role :{  //角色表单数据
            id:null,
            name:"",
            sn:"",

          },


        },
        roleEmp:{
          roleIds:[],
          eid : null
        },
        allRoles:[]
			}
		},
		methods: {
			handleCurrentChange(val) {
			  //改变当前显示页数
        this.query.currentPage = val;
        this.getAddress();
			},
      handleSizeChange(val) {
			  //改变每页显示条数
        this.query.pageSize = val;
        this.getAddress();
      },
			//获取用户列表
			getAddress() {
				this.listLoading = false;
				this.$http.post("/address",this.query)
        .then(result => {
          result = result.data;
          this.pageInfo = result.obj;
        })
        .catch(result =>{
          this.$message({
            message: '网络错误!',
            type: 'error'
          });
        })
			},
      advancedQuery(){
        //初始化页面
        this.query.currentPage = 1;
        //加载数据到页面
        this.getAddress();
      },
			//删除
			handleDel: function (index, row) {
        this.$confirm('数据将无法恢复!', '警告', {
          type: 'warning'
        }).then(() => {
          //弹出加载窗口
          this.listLoading = true;
          this.$http.delete("/address/"+row.id)
              .then(result => {
                //操作成功进入then,关闭加载窗口
                this.listLoading = false;
                result = result.data;
                if(result.success){
                  this.$message({
                    message: '删除成功!',
                    type: 'success'
                  });
                  //删除完成后刷新页面
                  this.advancedQuery();
                }else{
                  this.$message({
                    message: '删除失败!',
                    type: 'error'
                  });
                }
              })
              .catch(result => {
                this.$message({
                  message: '网络错误!',
                  type: 'error'
                });
              })
        }).catch(() => {
          this.$message({
            message: '取消删除!',
            type: 'success'
          });
        });
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        //弹出界面
        this.saveFormVisible = true;
        this.getDeptTree();
        this.$http.get("/address").then(result =>{
          result = result.data;
          //Object.assign({}, row);数据回显
          //Object.assign()方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。它将返回目标对象。
          //Object.assign方法的第一个参数是目标对象，后边的其他参数都是源对象；
          this.saveForm = Object.assign({}, row);
          this.saveForm.department = row.department.id;
        }).catch(result =>{

        })
        this.saveLoading = false;
      },
			//显示新增界面
			handleAdd: function () {
        //弹出界面
        this.saveFormVisible = true;
        //初始化
        this.saveForm = {
          id:null,
          username: '',
          email:"",
          password:"",
          age:0,
          department:{
            id:null,
            name:""
          },
          headImage:""
        }

        this.getDeptTree();
      },
      // 查询部门树
      getDeptTree(){
        this.$http.get("/department/tree")
            .then(result => {
              result = result.data;
              console.log("部门树");
              console.log(result);
              this.deptTree = result.obj;
            }).catch(result => {
          this.$message({ message: '查询部门树失败',type: 'error'});
        })
      },

			//保存
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              let para = Object.assign({}, this.saveForm);
              // 处理父部门
              if (para.department)
              para.department = {"id" : para.department[para.department.length-1]}
              console.log("para")
              console.log(para)
              this.$http.put("/address",para)
                  .then(result => {
                    result = result.data;
                    if(result.success){
                      this.advancedQuery();
                      this.saveLoading = false;
                      this.saveFormVisible = false;
                      this.$message({ message: '保存成功',type: 'success'});
                    }else{
                      this.$message({ message: result.message,type: 'error'});
                    }
                  })
            });
          }
        });
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
      batchDelete: function () {
        //从sels中获取所有被选中的id
        var ids = this.sels.map(item => item.id);
        this.$confirm('数据将无法恢复!', '警告', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //除get请求其他请求传参应该加上requestBody否侧无数据
          this.$http.patch("/address",ids)
              .then(result => {
                //无论成功与否都要关闭加载窗口
                this.listLoading = false;
                //后端返回的数据会被包在data中
                result = result.data;
                if(result.success){
                  this.$message({
                    message: '删除成功!',
                    type: 'success'
                  });
                  //刷新页面
                  this.advancedQuery();
                }else{
                  this.$message({
                    message: '删除失败!',
                    type: 'error'
                  });
                }
              })
              .catch(result => {
                this.$message({
                  message: '网络错误!',
                  type: 'error'
                });
              })
        }).catch(() => {
          this.$message({
            message: '网络错误!',
            type: 'error'
          });
        });
      },
      //设置角色
      handleSetRole(index,row){
			  //显示角色界面
        this.roleDisplay(index,row);
        //回显角色
        this.getRoles();

      },
      //显示角色界面
      roleDisplay(index,row){
        this.roleFormVisible = true;
        this.saveRoleForm.eForm = Object.assign({}, row);

        this.$http.get("/role/getRoles/" + this.saveRoleForm.eForm.id)
            .then(result =>{
              result = result.data;
              this.roleEmp.roleIds = result.obj;
            })



        console.log("saveRoleForm")
        console.log(this.saveRoleForm)


      },
      //保存角色
      roleSubmit(){

			  this.roleLoading = true;
        console.log("ids")
        console.log(this.roleEmp)
        //字段名必须一致否则无法传输数据
			  this.$http.put("/role/saveRoles",this.roleEmp)
            .then(result =>{
              result = result.data;
              if (result.success){
                this.$message({
                  message: '保存成功!',
                  type: 'success'
                });

              }else {
                this.$message({
                  message: '保存失败!',
                  type: 'error'
                });
              }
              //关闭
              this.roleLoading = false;
              this.roleFormVisible = false;
            })
            .catch(result =>{
              this.$message({
                message: '网络错误!',
                type: 'error'
              });
            })
      },
      //获取所有角色
      getRoles() {
        this.listLoading = false;
        this.$http.get("/role")
            .then(result => {
              result = result.data;
              this.roles = result.obj;
            })
            .catch(result =>{
              this.$message({
                message: '网络错误!',
                type: 'error'
              });
            })
      },

      handleCheck() {

        this.roleEmp.eid = this.saveRoleForm.eForm.id;


      },

		},
		mounted() {
			this.getAddress();
		}
	}

</script>

<style scoped>

</style>